package com.googlecode.mylyn.core.client;

import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.mylyn.tasks.core.TaskRepository;

import com.google.common.collect.Maps;

/**
 * Default implementation of {@link IGoogleCodeClientManager}.
 *
 * <p>This class should only be instantiated once and registered for repository
 * changes.</p>
 */
@ThreadSafe
public final class GoogleCodeClientManager implements IGoogleCodeClientManager {

    //TODO this class need to be actually registered by the UI plugin

    @GuardedBy("this")
    private final Map<String, IGoogleCodeClient> clientByUrl;

    /**
     * Default constructor, should not be instantiated more than once.
     */
    public GoogleCodeClientManager() {
      clientByUrl = Maps.newHashMap();
    }

    public IGoogleCodeClient getClient(@Nonnull TaskRepository repository) throws CoreException {
        Assert.isNotNull(repository);
        IGoogleCodeClient client = clientByUrl.get(repository.getRepositoryUrl());
        if (client == null) {
            client = new GDataGoogleCodeClient(repository);
            clientByUrl.put(repository.getRepositoryUrl(), client);
        }
        return client;
    }

    public synchronized void repositoryAdded(TaskRepository repository) {
        //ignore for now, create client lazily in #getClient
    }

    public synchronized void repositoryRemoved(TaskRepository repository) {
        clientByUrl.remove(repository.getUrl());
    }

    public synchronized void repositorySettingsChanged(TaskRepository repository) {
        this.repositoryRemoved(repository);
    }

    public synchronized void repositoryUrlChanged(TaskRepository repository, String oldUrl) {
        this.repositorySettingsChanged(repository);
    }

}
